package cn.tedu.knows.faq.service.impl;


import cn.tedu.knows.commons.exception.ServiceException;
import cn.tedu.knows.commons.model.Answer;
import cn.tedu.knows.commons.model.Question;
import cn.tedu.knows.commons.model.User;
import cn.tedu.knows.faq.mapper.AnswerMapper;
import cn.tedu.knows.faq.mapper.QuestionMapper;
import cn.tedu.knows.faq.service.IAnswerService;
import cn.tedu.knows.faq.vo.AnswerVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-05-25
 */
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements IAnswerService {

    @Resource
    private RibbonClient ribbonClient;
    @Resource
    private AnswerMapper answerMapper;
    @Override
    public Answer saveAnswer(AnswerVo answerVo, String username) {
        //获得用户信息
        User user=ribbonClient.getUser(username);
        //实例化对象
        Answer answer=new Answer()
                .setContent(answerVo.getContent())
                .setQuestId(answerVo.getQuestionId())
                .setUserId(user.getId())
                .setUserNickName(user.getNickname())
                .setCreatetime(LocalDateTime.now())
                .setLikeCount(0)
                .setAcceptStatus(0);
        //开始新增
        int num=answerMapper.insert(answer);
        if(num!=1){
            throw new ServiceException("新增失败!");
        }
        return answer;
    }

    @Override
    public List<Answer> getAnswersByQuestionId(Integer questionId) {

        // 修改了调用的方法
        // 现在这个方法是查询所有回答以及回答中包含的评论
        List<Answer> answers=answerMapper
                .findAnswersByQuestionId(questionId);
        //返回 answers
        return answers;
    }

    @Resource
    private QuestionMapper questionMapper;

    @Override
    @Transactional
    public boolean accept(Integer answerId) {
        //获得answer对象
        Answer answer=answerMapper.selectById(answerId);
        if(answer.getAcceptStatus()==1){
            throw new ServiceException("回答已经被采纳了!");
        }
        //修改回答的状态
        int num=answerMapper
                .updateAcceptStatus(1,answerId);
        if(num!=1){
            throw new ServiceException("数据库异常");
        }
        //修改问题状态
        num=questionMapper.updateStatus(Question.SOLVED,
                    answer.getQuestId());
        if(num!=1){
            throw new ServiceException("数据库异常");
        }
        return true;
    }
}
